package cn.com.platform.web.manage.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import cn.com.easy.exception.BusinessException;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.controller.BaseController;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.permission.web.dto.PageRequestParamDTO;
import cn.com.easy.utils.DateUtils;
import cn.com.easy.utils.Page;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;
import cn.com.platform.dao.BlockDao;
import cn.com.platform.dao.BlockItemDao;
import cn.com.platform.entity.AccessoryEntity;
import cn.com.platform.entity.BlockEntity;
import cn.com.platform.entity.BlockItemEntity;
import cn.com.platform.mybatis.BlockItemMybatisDao;
import cn.com.platform.service.BlockItemService;
import cn.com.platform.utils.UploadFileUtil;
import cn.com.platform.web.manage.dto.BlockItemDto;
import cn.com.platform.web.manage.dto.BlockItemQueryParamDto;

import com.github.miemiedev.mybatis.paginator.domain.PageList;

/**
 * 内容推荐管理
 * 
 * @author lmh 2016年9月22日
 * 
 */
@Controller
@RequestMapping("/manage/block/item")
public class BlockItemManageController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(BlockItemManageController.class);

	/** 内容推荐Dao */
	@Autowired
	private BlockItemDao blockItemDao;

	/** 推荐位Dao */
	@Autowired
	private BlockDao blockDao;

	/** 内容推荐MybatisDao */
	@Autowired
	private BlockItemMybatisDao blockItemMybatisDao;
	/** 内容推荐服务 */
	@Autowired
	private BlockItemService blockItemService;

	/**
	 * 获取内容推荐列表
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author lmh 2016年8月19日
	 */
	@UrlReserveAnotion("获取内容推荐列表")
	@RequestMapping("/list")
	public void findBlockItemList(HttpServletRequest req, HttpServletResponse res, PageRequestParamDTO paramDto, final BlockItemQueryParamDto param) {
		try {
			if (paramDto.getSortName() == null) {
				paramDto.setSortName("createTime");
				paramDto.setSortOrder("desc");
			}
			PageList<BlockItemDto> pageObject = blockItemMybatisDao.queryBlockItems(param, paramDto.buildMyBatisPageRequest());
			for (BlockItemDto blockItemDto : pageObject) {
				if (blockItemDto.getExpireTime() != null) {
					blockItemDto.setExpireTimeString(DateUtils.formatDate(blockItemDto.getExpireTime(), "yyyy-MM-dd"));
				}
			}
			Page<BlockItemDto> page = PageUtils.getPage(pageObject);
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有内容推荐异常.", ex);
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", false, "获取所有内容推荐异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 保存或更新内容推荐
	 * 
	 * @param request
	 * @param response
	 * @param BlockItemDto
	 * @author lmh 2016年8月17日
	 */
	@UrlReserveAnotion("保存或更新内容推荐")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void saveOrUpdateBlockItem(HttpServletRequest request, HttpServletResponse response, MultipartFile file, BlockItemDto blockItemDto) {
		try {
			UserModel user = getCurrentUser(request);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			// 图片操作
			if (file != null && file.getSize() > 0) {
				String name = "" + new Date().getTime();
				String path = "photo/block/blockItemPicImg";
				// 保存图片
				AccessoryEntity accessory = UploadFileUtil.uploadFile(file, path, name, user.getId());
				String photo = accessory.getPath() + "/" + accessory.getName();
				blockItemDto.setPhoto(photo);
			}
			blockItemService.saveOrUpdate(blockItemDto, user);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
		} catch (Exception ex) {
			logger.error("提交内容推荐信息异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交内容推荐信息异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 删除内容推荐
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author lmh 2016年8月17日
	 */
	@UrlReserveAnotion("删除内容推荐")
	@RequestMapping(value = "/delete")
	public void deleteBlockItem(HttpServletRequest request, HttpServletResponse response, BlockItemEntity blockItemEntity) {
		try {
			if (blockItemEntity.getId() == null) {
				throw new BusinessException("内容推荐id不能为空");
			}
			if (StringUtils.isBlank(blockItemEntity.getTitle())) {
				throw new BusinessException("内容推荐标题不能为空");
			}
			// 删除内容推荐
			BlockItemEntity blockItemEntityTemp = blockItemDao.findByIdAndTitle(blockItemEntity.getId(), blockItemEntity.getTitle());
			if (blockItemEntityTemp == null) {
				throw new BusinessException("未找到改内容推荐");
			} else {
				blockItemDao.delete(blockItemEntityTemp);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, "删除成功"));
			}
		} catch (Exception ex) {
			logger.error("删除内容推荐异常，id:" + blockItemEntity.getTitle(), ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "删除内容推荐异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 获取推荐位
	 * 
	 * @param request
	 * @param response
	 * @author lmh 2016年8月23日
	 */
	@UrlReserveAnotion("获取推荐位")
	@RequestMapping(value = "/findBlock")
	public void findBlock(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<BlockEntity> blockPageEntities = blockDao.findByDeleteStatus(false);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, blockPageEntities));
		} catch (Exception ex) {
			logger.error("获取推荐位异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取推荐位异常.ex:" + ex.getLocalizedMessage()));
		}
	}
}
